package com.kly.sc.api.integration.userplatform.util;


import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.kly.sc.api.infras.exception.ApplicationException;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;

/**
 * @author linqu
 */
public class ApiClient {
    private String auth;
    private final String DATA = "data";
    private final String CODE = "code";
    private final String MSG = "msg";
    private final int SUCCESS_CODE = 0;
    private final int STATUS_OK = 200;
    private final int STATUS_MULTIPLE_CHOICE = 300;
//    @Value("${user.api.url}")
    private String API_URL;

    public ApiClient(String auth) {
        this.auth = auth;
    }

    /**
     * http post请求
     */
    public JSONObject post(String path, JSONObject requestObject) throws ApplicationException {
        Response response = ApiUtils.postRequest(API_URL, path, requestObject, this.auth);
        return this.processResponse(response);
    }

    /**
     * https post请求
     */
    public Object postWithSSL(String path, JSONObject requestObject, Class clazz) throws ApplicationException {
        Response response = ApiUtils.postRequestSSL(API_URL, path, requestObject, this.auth);
        return this.processResponse(response);
    }


    private JSONObject parseResponse(JSONObject jsonObject) throws ApplicationException {
        final Integer code = jsonObject.getInteger(CODE);
        if (code == SUCCESS_CODE) {
            if (jsonObject.containsKey(DATA)) {
                return jsonObject;
            } else {
                throw new ApplicationException("Unable to parse response");
            }
        }
        throw new ApplicationException(jsonObject.getString(MSG));


    }



    JSONObject processResponse(Response response) throws ApplicationException {
        if (response == null) {
            throw new ApplicationException("Invalid Response from server");
        } else {
            int statusCode = response.code();
            String responseBody = null;
            JSONObject responseJson = null;

            try {
                responseBody = response.body().string();
                responseJson = JSONObject.parseObject(responseBody);
            } catch (IOException e) {
                throw new ApplicationException(e.getMessage());
            }

            if (statusCode >= STATUS_OK && statusCode < STATUS_MULTIPLE_CHOICE) {
                return this.parseResponse(responseJson);
            } else {
                this.throwException(statusCode, responseJson);
                return null;
            }
        }
    }

    private void throwException(int statusCode, JSONObject responseJson) throws ApplicationException {
        if (responseJson.containsKey("msg")) {
            String code = responseJson.getString("code");
            String description = responseJson.getString("msg");
            throw new ApplicationException(code + ":" + description);
        } else {
            this.throwServerException(statusCode, responseJson.toString());
        }
    }

    private void throwServerException(int statusCode, String responseBody) throws ApplicationException {
        StringBuilder sb = new StringBuilder();
        sb.append("Status Code: ").append(statusCode).append("\n");
        sb.append("Server response: ").append(responseBody);
        throw new ApplicationException(sb.toString());
    }

}